package de.projectgoodmorning.alarm.activities;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import de.projectgoodmorning.alarm.AlarmController;
import de.projectgoodmorning.alarm.R;
import de.projectgoodmorning.alarm.activities.util.Actionbar;
import de.projectgoodmorning.alarm.activities.util.AlarmNotificationManager;
import de.projectgoodmorning.alarm.dialogs.ConfirmDialog;
import de.projectgoodmorning.alarm.model.Configuration;
import de.projectgoodmorning.alarm.storage.AlarmStorage;
import de.projectgoodmorning.alarm.storage.ConfigStorage;
import de.projectgoodmorning.alarm.storage.IdCounter;
import de.projectgoodmorning.alarm.util.RsrcHelper;

/**
 * Die SettingsActivity Klasse bietet dem Nutzer Einstellungen
 * an der Anwendung vorzunehmen.
 * Darunter befindet sich die Snoozezeit, das Wecksignal und die Funktion
 * die Anwendung zurueck zusetzen.
 */
public class SettingsActivity extends Activity {

	private static final int RINGTONE_DIALOG = 1;
	
	private Button reset, chooseRingtone;
	private Spinner snoozeTime;
	
	private AlarmController alarmController;
	private AlarmStorage alarmStorage;
	private ConfigStorage configStorage;
	private Configuration config;
	
	@Override
	public void onCreate( Bundle savedInstanceState ) {
		super.onCreate( savedInstanceState );
		setContentView( R.layout.activity_settings );

		reset = ( Button ) findViewById( R.id.resetButton );
		chooseRingtone = ( Button ) findViewById( R.id.chooseRingtoneButton );
		snoozeTime = ( Spinner ) findViewById( R.id.snoozetimeSpinner );

		Actionbar action = new Actionbar( this );
		action.setOnBackButtonClicked( new View.OnClickListener() {
			@Override
			public void onClick( View v ) {
				onBackPressed();
			}
		} );
		
		try {
			bindService( new Intent( this, AlarmController.class ), 
					alarmControllerServiceConnection, Context.BIND_AUTO_CREATE );
		} catch( Exception e ) {
		}
		
		alarmStorage = new AlarmStorage( this );
		
		configStorage = new ConfigStorage( this );
		config = configStorage.getConfig();
		
		initComponents();
	}

	@Override
	protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
		super.onActivityResult( requestCode, resultCode, data );
		
		if( requestCode == RINGTONE_DIALOG && resultCode == RESULT_OK ) {
			Uri uri = data.getParcelableExtra( RingtoneManager.EXTRA_RINGTONE_PICKED_URI );
			if( uri != null ) {
				config.ringtoneAddress = uri;
				configStorage.setConfig( config );
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		if( alarmController != null ) {
			unbindService( alarmControllerServiceConnection );
		}
	}
	
	/////////// Helpers /////////////////////////////////////
	
	private void initComponents() {
		reset.setOnClickListener( new View.OnClickListener() {
			@Override
			public void onClick( View v ) {
				ConfirmDialog dialog = new ConfirmDialog( SettingsActivity.this );
				dialog.setOnConfirmClicked( new OnClickListener() {
					@Override
					public void onClick( DialogInterface dialog, int which ) {
						resetApp();
					}
				} );
				
				dialog.setOnCancelClicked( new OnClickListener() {
					@Override
					public void onClick( DialogInterface dialog, int which ) {
						dialog.cancel();
					}
				} );
				
				dialog.show();
			}
		} );
		
		chooseRingtone.setOnClickListener( new View.OnClickListener() {
			@Override
			public void onClick( View v ) {
				showRingtonePicker();
			}
		} );
		
		int size = 10;
		String[] snoozeModel = new String[size];
		for( int i=0; i<size; i++ ) {
			snoozeModel[i] = (i + 1) + " " + RsrcHelper.getString( R.string.minutes, this );
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>( 
				this, android.R.layout.simple_spinner_item, snoozeModel );
				
		adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
		snoozeTime.setAdapter( adapter );
		
		snoozeTime.setSelection( config.snoozeTimeInMinutes-1 );
		snoozeTime.setOnItemSelectedListener( new OnItemSelectedListener() {
			@Override
			public void onItemSelected( AdapterView<?> arg0, View arg1, int position, long arg3 ) {
				config.snoozeTimeInMinutes = position+1;
				configStorage.setConfig( config );
			}

			@Override
			public void onNothingSelected( AdapterView<?> arg0 ) {
			}
		} );
	}
	
	private void resetApp() {
		RsrcHelper res = new RsrcHelper( this );
		
		try {
			AlarmNotificationManager notificationManager = new AlarmNotificationManager( this );
			notificationManager.deactiveAll();
			
			alarmController.removeAllAlarms();
			configStorage.removeConfig();
			alarmStorage.removeAll();
			new IdCounter( getApplicationContext() ).reset();
			
			alarmStorage.loadAlarms();
			Toast.makeText( this, res.getString( R.string.msg_resetSuccess ), 
					Toast.LENGTH_SHORT ).show();
		} catch( Exception e ) {
			Toast.makeText( this, res.getString( R.string.msg_resetNotSuccess ), 
					Toast.LENGTH_SHORT ).show();
		}
		
		config = configStorage.getConfig();
		snoozeTime.setSelection( config.snoozeTimeInMinutes-1 );
	}
	
	private void showRingtonePicker() {
		Intent intent = new Intent( RingtoneManager.ACTION_RINGTONE_PICKER );
		intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION );
		intent.putExtra( RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false );
		
		intent.putExtra( RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, config.ringtoneAddress );
		
		String dialogTitle = RsrcHelper.getString( R.string.chooseRingtone, this );
		intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TITLE, dialogTitle );
		
		startActivityForResult( intent, RINGTONE_DIALOG );
	}
	
	/////////////////////////////////////////////////////////
	
	/////////// SERVICE /////////////////////////////////////
	
	private ServiceConnection alarmControllerServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected( ComponentName name ) {
			alarmController = null;
		}
		@Override
		public void onServiceConnected( ComponentName name, IBinder service ) {
			alarmController = ( ( AlarmController.LocalBinder ) service ).getService();
		}
	};
	
}
